package com.ch.fitter;

import com.ch.config.RedisUtil;
import com.ch.entity.User;
import com.ch.entity.appproprity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;


@Component
public class myfitter implements GlobalFilter , Order {
    @Autowired
    private appproprity appproprity;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        String[] exclude=appproprity.getExclude().toArray(new String[0]);
        for (String item : exclude) {
            if (path.startsWith(item)){
                return chain.filter(exchange);
            }
        }
        String authorization = exchange.getRequest().getHeaders().get("authorization").get(0);
        User user= (User) redisUtil.get(authorization);
        if (user!=null){
            return chain.filter(exchange);
        }
        else {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

    }

    @Override
    public int value() {
        return 0;
    }

}
